package com.bryantkobe.myspringcode.factory;

import com.bryantkobe.myspringcode.exception.BusinessException;
import com.bryantkobe.myspringcode.exception.ExceptionEnum;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @description: 业务异常工厂
 * @author: alienwarezzl
 * @date: 2025/9/23
 */
@Component
public class BusinessExceptionFactory {
    /**
     * 创建业务异常 - 确保异常能被Spring异常机制正确处理
     */
    public BusinessException create(ExceptionEnum exceptionEnum, Object... args) {
        String message = args.length > 0 ?
                String.format(exceptionEnum.getDefaultMessage(), args) :
                exceptionEnum.getDefaultMessage();

        BusinessException exception = new BusinessException(
                exceptionEnum.getErrorCode(), message);

        // 添加调试信息
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        if (stackTrace.length > 3) { // 跳过工厂方法本身的调用栈
            exception.setStackTrace(new StackTraceElement[]{
                    stackTrace[3] // 获取调用断言方法的位置
            });
        }

        return exception;
    }

    /**
     * 创建带参数的异常
     */
    public BusinessException createWithParams(ExceptionEnum exceptionEnum,
                                              Map<String, Object> params,
                                              Object... args) {
        BusinessException exception = create(exceptionEnum, args);
        if (params != null) {
            params.forEach(exception::withParam);
        }
        return exception;
    }
}
